package com.example.administrator.reader;

import android.content.Intent;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SimpleItemAnimator;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;

import android.view.animation.AnimationUtils;
import android.view.animation.LayoutAnimationController;
import android.widget.TextView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity {
    public DrawerLayout mDrawerLayout;//侧滑抽屉布局
    public NavigationView mNavigationView;//布局需要的控件
    public String API_URL = "https://news-at.zhihu.com/api/4/news/latest";//最新消息的url
    public String detail_URL = "https://news-at.zhihu.com/api/4/news/";//点击每一个item的url
    public static String date = "";//日期
    public String url = "";//拿到每个item的id然后跟detailurl拼接成url
    public static String share_url = "";//去拿每个item的第二个活动的url；
    ArrayList<ZhiHu> zhiHuArrayList = new ArrayList<>();//item的数据
    RecyclerView recyclerView;
    TextView date_title;
    static List<String> imageUrls = new ArrayList<>();//头部滑动布局的最新信息的的图像
    static List<String> itemid = new ArrayList<>();//头部滑动布局的最新信息的的id
    static final List<String> descriptions = new ArrayList<>();//头部滑动布局的最新信息的的title
    Zhihuadapter zhihuadapter;
    private boolean first = true;
    private static List<Integer> date_postion = new ArrayList<>();
    private String date_deil = "";//细节的日期
    List<Integer> getDate_postion() {
        return date_postion;
    }
    static HashMap<Integer, String> hashMap = new HashMap<>();//日期的位置和日期时间
    SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");//日期的格式，api拼接
    SimpleDateFormat format2 = new SimpleDateFormat("MM月dd日 EE");//展示的日期格式
    Calendar c = Calendar.getInstance();//日历
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mDrawerLayout = (DrawerLayout) findViewById(R.id.id_drawer_layout);
        mNavigationView = (NavigationView) findViewById(R.id.id_nv_menu);
        recyclerView = findViewById(R.id.recyclerview);
        date_title = findViewById(R.id.title);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(linearLayoutManager);
        Toolbar toolbar = findViewById(R.id.id_toolbar);
        setSupportActionBar(toolbar);
        final ActionBar ab = getSupportActionBar();
        ab.setDisplayHomeAsUpEnabled(true);
        ab.setDisplayShowTitleEnabled(false);
        setupDrawerContent(mNavigationView);
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                //点击状态改变的回调方法
            }
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                if (isSlideToBottom(recyclerView)) {
                    Second_net();
                }
            }
        });//上啦加载
        firstnet();
    }
    public static boolean isSlideToBottom(RecyclerView recyclerView) {
        if (recyclerView == null) return false;
        if (recyclerView.computeVerticalScrollExtent() + recyclerView.computeVerticalScrollOffset()
                >= recyclerView.computeVerticalScrollRange())
            return true;
        return false;
    }//判断是否滑到低端
    public void firstnet() {
        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder()
                .url(API_URL)
                .build();
        Log.d("qqq", API_URL);
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.d("zhaojias", "onFailure: " + e.getMessage());
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String res = response.body().string();
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(res);
                    JSONArray top_stories = jsonObject.getJSONArray("top_stories");
                    JSONArray stories = jsonObject.getJSONArray("stories");
                    Log.d("zjs", stories.toString());
                    Log.d("zjs", top_stories.toString());
                    for (int i = 0; i < top_stories.length(); i++) {
                        JSONObject jsonObject1 = top_stories.getJSONObject(i);
                        imageUrls.add(jsonObject1.getString("image"));
                        descriptions.add(jsonObject1.getString("title"));
                        itemid.add(jsonObject1.getString("id"));
                    }
                    for (int i = 0; i < stories.length(); i++) {
                        JSONObject jsonObject1 = stories.getJSONObject(i);
                        ZhiHu zhiHu = new ZhiHu(jsonObject1.getJSONArray("images"), jsonObject1.getString("title"), jsonObject1.getString("id"));
                        zhiHuArrayList.add(zhiHu);
                    }
                    Second_net();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.more, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            mDrawerLayout.openDrawer(GravityCompat.START);
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
    private void setupDrawerContent(NavigationView navigationView) {
        navigationView.setNavigationItemSelectedListener(
                new NavigationView.OnNavigationItemSelectedListener() {
                    @Override
                    public boolean onNavigationItemSelected(MenuItem menuItem) {
                        menuItem.setChecked(true);
                        mDrawerLayout.closeDrawers();
                        return true;
                    }
                });
    }
    public void Second_net() {
        date();
        date_postion.add(zhiHuArrayList.size() + 1);
        String Before_Url = "https://news-at.zhihu.com/api/4/news/before/" + date;
        hashMap.put(zhiHuArrayList.size() + 1, date_deil);
        Log.d("zjs", Before_Url);
        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder()
                .url(Before_Url)
                .build();
        Log.d("zjs", Before_Url);
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.d("zjs", "onFailure: " + e.getMessage());
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String res = response.body().string();
                Log.d("zjs", "here+ " + res);
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(res);
                    JSONArray stories = jsonObject.getJSONArray("stories");
                    Log.d("zjs", stories.toString());
                    for (int i = 0; i < stories.length(); i++) {
                        JSONObject jsonObject1 = stories.getJSONObject(i);
                        ZhiHu zhiHu = new ZhiHu(jsonObject1.getJSONArray("images"), jsonObject1.getString("title"), jsonObject1.getString("id"));
                        zhiHuArrayList.add(zhiHu);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                showResponse();
            }
        });
    }
    public void date() {
        Log.d("最新时间", date);
        if (first == true) {
            Date dNow = new Date();
            c.setTime(dNow);
        }
        c.add(Calendar.DAY_OF_MONTH, -1);
        Date dBefore = new Date();
        dBefore = c.getTime();
        Log.d("前一天", dBefore.toString());
        c.setTime(dBefore);
        date = format.format(dBefore);
        date_deil = format2.format(dBefore);
        //设置时间格式
    }
    public void showResponse() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (first == true) {
                    zhihuadapter = new Zhihuadapter(zhiHuArrayList, getApplicationContext());
                    recyclerView.setAdapter(zhihuadapter);
                    final LayoutAnimationController controller =
                            AnimationUtils.loadLayoutAnimation(getApplicationContext(), R.anim.layout_animation_fall_down);
                    recyclerView.setLayoutAnimation(controller);
//第一次有动画效果

                }
                if (first != true) {

                    zhihuadapter.notifyItemRangeInserted(date_postion.get(date_postion.size() - 1), zhiHuArrayList.size());
                }
                zhihuadapter.setOnItemClickListener(new Zhihuadapter.OnItemClickListener() {
                    @Override
                    public Void onitemclickview(View view, int position) {
                        ZhiHu zhiHu = zhiHuArrayList.get(position);
                        url = detail_URL + zhiHu.getId();
                        net();
                        return null;
                    }
                });
                first = false;
            }
        });
    }
    public void net() {
        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder()
                .url(url)
                .build();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.d("zjs", "onFailure: " + e.getMessage());
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String res = response.body().string();
                Log.d("url", res);
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(res);
                    share_url = jsonObject.getString("share_url");
                    Log.d("url", share_url);
                    Intent intent = new Intent(MainActivity.this, Main2Activity.class);
                    startActivity(intent);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }
}
